package edu.dlust.trading_platform;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBean.GoodsBean;
import edu.dlust.trading_platform.adapter.HomePageAdapter;

public class HomePageActivity extends AppCompatActivity {
    private LinearLayout publish,mine,chat;
    private EditText edit;
    private Button search;
    private ListView listview;
    private List<GoodsBean> list;
    private HomePageAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        navigater();
        findData();
        check();
        search_go();
        refresh();
    }

    private void navigater(){
        publish = findViewById(R.id.home_publish);
        publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomePageActivity.this, PublishActivity.class);
                startActivity(intent);
            }
        });
        mine = findViewById(R.id.home_main);
        mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomePageActivity.this,UserActivity.class);
                startActivity(intent);
                HomePageActivity.this.finish();
            }
        });
        chat = findViewById(R.id.home_chat);
        chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(HomePageActivity.this,ChatActivity.class);
                startActivity(intent);
            }
        });
    }

    private void findData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<GoodsBean> data = find();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        show(data);
                    }
                });
            }
        }).start();
    }

    private List<GoodsBean> find(){
        List<GoodsBean> lists = new ArrayList<>();
        String sql = "SELECT g.id, l.UName, g.Content, g.Fineness, g.Classification, g.Price, g.Type, g.Image FROM GOODS g INNER JOIN LOGINID l ON g.Uid = l.Uid WHERE g.Buyer IS NULL ORDER BY g.id DESC;";
        try {
            Connection con = MySQL.getConnection();
            PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                GoodsBean goodsBean = new GoodsBean();
                int id = rs.getInt("id");
                String UName = rs.getString("UName");
                String Content = rs.getString("Content");
                String Fineness = rs.getString("Fineness");
                String Classification = rs.getString("Classification");
                String Price = rs.getString("Price");
                String Type = rs.getString("Type");
                byte[] Image = rs.getBytes("Image");
                if (Image != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(Image, 0, Image.length);
                    goodsBean.setGImage(bitmap);
                }else {
                    goodsBean.setGImage(null);
                }

                goodsBean.setGid(id);
                goodsBean.setGName(UName);
                goodsBean.setGContent(Content);
                goodsBean.setGFineness(Fineness);
                goodsBean.setGClassification(Classification);
                goodsBean.setGPrice(Price);
                goodsBean.setGType(Type);

                lists.add(goodsBean);
            }
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lists;
    }

    private void show(List<GoodsBean> data){

        listview = findViewById(R.id.lv_list);
        if (list != null) {
            list.clear();
        }
        list = data;
        adapter = new HomePageAdapter(this, list);
        listview.setAdapter(adapter);
    }

    private void check(){
        listview = findViewById(R.id.lv_list);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                View clickedView = listview.getChildAt(position - listview.getFirstVisiblePosition());

                if (clickedView != null) {
                    // 找到显示goodsId的TextView，并获取其内容
                    TextView goodsIdTextView = clickedView.findViewById(R.id.goods_id);
                    String goodsId = goodsIdTextView.getText().toString();

                    // 创建Intent并传递goodsId到下一个Activity
                    Intent intent = new Intent(HomePageActivity.this, GoodsDetailsActivity.class);
                    intent.putExtra("goodsId", goodsId);
                    startActivity(intent);
                }
            }
        });
    }

    private void search_go(){
        search = findViewById(R.id.search);
        edit = findViewById(R.id.edit_search);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String thing = edit.getText().toString();
                if(thing.equals("")){
                    Toast.makeText(HomePageActivity.this, "搜索内容不能为空!", Toast.LENGTH_SHORT).show();
                }else {
                    Intent intent = new Intent(HomePageActivity.this, SearchActivity.class);
                    intent.putExtra("search", thing);
                    startActivity(intent);
                }
            }
        });
    }
    private void refresh(){
        swipeRefreshLayout = findViewById(R.id.home_swipeRefreshLayout);

        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                refreshData();
            }
        });

        // 初始化数据
        refreshData();
    }
    private void refreshData() {
        findData();
        swipeRefreshLayout.setRefreshing(false);
    }
}